package service

import (
	"context"
	"encoding/json"
	"fmt"
	"food-mgr/food-service/handler/model"
	"food-mgr/food-service/inits"
	"food-mgr/food-service/pkg"
	__ "food-mgr/food-service/proto"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"gorm.io/gorm"
	"image/png"
	"os"
	"time"
)

type Service struct {
	__.UnimplementedFoodServer
}

func (s Service) DelOrder(_ context.Context, in *__.DelOrderReq) (*__.DelOrderResp, error) {

	var order model.Order
	model.FindOrder(&order, in.Number)
	if in.Number != order.Number {
		return &__.DelOrderResp{
			Code: 200,
			Msg:  "没有此取件码",
		}, nil
	}
	err := model.DelOrder(&order, int(in.ID))
	if err != nil {
		return &__.DelOrderResp{
			Code: 0,
			Msg:  "核销失败",
		}, nil
	}
	return &__.DelOrderResp{
		Code: 200,
		Msg:  "核销成功",
	}, nil
}
func (s Service) ListPick(_ context.Context, in *__.ListPickReq) (*__.ListPickResp, error) {

	var pick []model.Pick
	err := model.ListPick(&pick, in.Address)
	if err != nil {
		return &__.ListPickResp{
			Code: 0,
			Msg:  "查看失败",
			List: nil,
		}, nil
	}
	var pickList []*__.ListPick
	for _, m := range pick {

		list := &__.ListPick{
			Name:    m.Name,
			Address: m.Address,
			Year:    m.Year,
		}
		pickList = append(pickList, list)
	}
	return &__.ListPickResp{
		Code: 200,
		Msg:  "查看成功",
		List: pickList,
	}, nil
}
func (s Service) ListShop(_ context.Context, in *__.ListShopReq) (*__.ListShopResp, error) {

	var shop []model.Shop
	err := model.ListShop(&shop)
	if err != nil {
		return &__.ListShopResp{
			Code: 0,
			Msg:  "查询失败",
			List: nil,
		}, nil
	}
	var shopList []*__.ListShop
	for _, m := range shop {

		list := &__.ListShop{
			Name:   m.Name,
			Price:  float32(m.Price),
			Num:    int64(m.Num),
			Status: m.Status,
			Count:  int64(m.Count),
		}
		shopList = append(shopList, list)
	}
	ShopKey := fmt.Sprintf("%s", "shop")
	marshal, err := json.Marshal(&shop)
	if err != nil {
		return nil, err
	}
	inits.Rdb.Set(inits.Ctx, ShopKey, marshal, time.Minute*5)
	return &__.ListShopResp{
		Code: 200,
		Msg:  "查询成功",
		List: shopList,
	}, nil
}
func (s Service) ListEval(_ context.Context, in *__.ListEvalReq) (*__.ListEvalResp, error) {

	var biz model.Biz
	model.FindBiz(&biz, int(in.BizId))
	if biz.ID == 0 {
		return &__.ListEvalResp{
			Code: 0,
			Msg:  "没有该商家",
			List: nil,
		}, nil
	}
	var eval []model.Eval
	err := model.ListEval(&eval, int(in.BizId))
	if err != nil {
		return &__.ListEvalResp{
			Code: 0,
			Msg:  "查看失败",
			List: nil,
		}, nil
	}
	var evalList []*__.ListEval
	for _, m := range eval {

		list := &__.ListEval{
			UserId:  int64(m.UserId),
			ShopId:  int64(m.ShopId),
			BizId:   int64(m.BizId),
			Score:   float32(m.Score),
			Context: m.Context,
		}
		evalList = append(evalList, list)
	}
	return &__.ListEvalResp{
		Code: 200,
		Msg:  "查看成功",
		List: evalList,
	}, nil
}
func (s Service) CreateEval(_ context.Context, in *__.CreateEvalReq) (*__.CreateEvalResp, error) {

	var biz model.Biz
	model.FindBiz(&biz, int(in.BizId))
	if biz.ID == 0 {
		return &__.CreateEvalResp{
			Code: 0,
			Msg:  "未找到该商家",
		}, nil
	}
	var eval model.Eval
	eval = model.Eval{
		UserId:  int(in.UserId),
		ShopId:  int(in.ShopId),
		BizId:   int(in.BizId),
		Score:   float64(in.Score),
		Context: in.Context,
	}
	err := model.CreateEval(&eval)
	if err != nil {
		return &__.CreateEvalResp{
			Code: 0,
			Msg:  "评价失败",
		}, nil
	}
	return &__.CreateEvalResp{
		Code: 200,
		Msg:  "评价成功",
	}, nil
}
func (s Service) UpdateSlot(_ context.Context, in *__.UpdateSlotReq) (*__.UpdateSlotResp, error) {

	var slot model.Slot
	slot = model.Slot{
		Model: gorm.Model{
			ID: uint(in.ID),
		},
		Status: in.Status,
	}
	err := model.UpdateSlot(&slot, int(in.ID))
	if err != nil {
		return &__.UpdateSlotResp{
			Code: 0,
			Msg:  "状态同步失败",
		}, nil
	}
	return &__.UpdateSlotResp{
		Code: 200,
		Msg:  "状态同步成功",
	}, nil
}
func (s Service) ListSlot(_ context.Context, in *__.ListSlotReq) (*__.ListSlotResp, error) {

	var slot []model.Slot
	err := model.ListSlot(&slot)
	if err != nil {
		return &__.ListSlotResp{
			Code: 0,
			Msg:  "查询失败",
			List: nil,
		}, nil
	}
	var slotList []*__.ListSlot
	for _, m := range slot {

		list := &__.ListSlot{
			UserId: m.UserId,
			BizId:  int64(m.BizId),
			Year:   m.Year,
			Tel:    m.Tel,
			Status: m.Status,
		}
		slotList = append(slotList, list)
	}
	return &__.ListSlotResp{
		Code: 200,
		Msg:  "查询成功",
		List: slotList,
	}, nil
}
func (s Service) CreateSlot(_ context.Context, in *__.CreateSlotReq) (*__.CreateSlotResp, error) {

	var biz model.Biz
	model.FindBiz(&biz, int(in.BizId))
	if biz.ID == 0 {
		return &__.CreateSlotResp{
			Code: 0,
			Msg:  "该商家不存在",
		}, nil
	}
	var slot model.Slot
	slot = model.Slot{
		UserId: in.UserId,
		BizId:  int(in.BizId),
		Year:   in.Year,
		Tel:    in.Tel,
		Status: in.Status,
	}
	err := model.CreateSlot(&slot)
	if err != nil {
		return &__.CreateSlotResp{
			Code: 0,
			Msg:  "预约失败",
		}, nil
	} else {
		qrCode, _ := qr.Encode("http://www.topgoer.com", qr.M, qr.Auto)

		qrCode, _ = barcode.Scale(qrCode, 256, 256)

		file, _ := os.Create("slot.png")
		defer file.Close()

		png.Encode(file, qrCode)
	}
	return &__.CreateSlotResp{
		Code: 200,
		Msg:  "预约成功",
	}, nil
}
func (s Service) ListBiz(_ context.Context, in *__.ListBizReq) (*__.ListBizResp, error) {

	var biz []model.Biz
	err := model.ListBiz(&biz, in.Name)
	if err != nil {
		return &__.ListBizResp{
			Code: 0,
			Msg:  "查询失败",
			List: nil,
		}, nil
	}
	var BizList []*__.ListBiz
	for _, m := range biz {

		list := &__.ListBiz{
			Name:    m.Name,
			Address: m.Address,
			Status:  m.Status,
			Score:   float32(m.Score),
		}
		BizList = append(BizList, list)
	}
	return &__.ListBizResp{
		Code: 200,
		Msg:  "查询成功",
		List: BizList,
	}, nil
}
func (s Service) ListRider(_ context.Context, in *__.ListRiderReq) (*__.ListRiderResp, error) {

	var rider []model.Rider
	err := model.ListRider(&rider)
	if err != nil {
		return &__.ListRiderResp{
			Code: 0,
			Msg:  "查看失败",
			List: nil,
		}, nil
	}
	var RiderList []*__.ListRider
	for _, m := range rider {

		list := &__.ListRider{
			UserId:  int64(m.UserId),
			BizId:   int64(m.BizId),
			OrderId: int64(m.OrderId),
			Status:  m.Status,
			Count:   int64(m.Count),
		}
		RiderList = append(RiderList, list)
	}
	return &__.ListRiderResp{
		Code: 200,
		Msg:  "查询成功",
		List: RiderList,
	}, nil
}
func (s Service) CreateRider(_ context.Context, in *__.CreateRiderReq) (*__.CreateRiderResp, error) {

	var rider model.Rider
	rider = model.Rider{
		UserId:  int(in.UserId),
		BizId:   int(in.BizId),
		OrderId: int(in.OrderId),
		Status:  in.Status,
	}
	err := model.CreateRider(&rider)
	if err != nil {
		return &__.CreateRiderResp{
			Code: 0,
			Msg:  "骑手接单失败",
		}, nil
	} else {
		var order model.Order
		order = model.Order{
			Model: gorm.Model{
				ID: uint(in.OrderId),
			},
			Status: "取餐中",
		}
		model.UpdateOrder(&order, int(in.OrderId))
	}
	return &__.CreateRiderResp{
		Code: 200,
		Msg:  "骑手接单成功",
	}, nil
}
func (s Service) ListOrder(_ context.Context, in *__.ListOrderReq) (*__.ListOrderResp, error) {

	var order []model.Order
	err := model.ListOrder(&order, int(in.Page), int(in.Size), in.BizId, int(in.UserId), in.Status)
	if err != nil {
		return &__.ListOrderResp{
			Code: 0,
			Msg:  "查询失败",
			List: nil,
		}, nil
	}
	var orderList []*__.ListOrder
	for _, m := range order {

		list := &__.ListOrder{
			UserId:   int64(m.UserId),
			ShopId:   int64(m.ShopId),
			OrderSn:  m.OrderSn,
			Address:  m.Address,
			Quantity: int64(m.Quantity),
			Money:    float32(m.Money),
			Status:   m.Status,
			BizId:    int64(m.BizId),
		}
		orderList = append(orderList, list)
	}
	marshal, err := json.Marshal(&order)
	if err != nil {
		return nil, err
	}
	orderKey := fmt.Sprintf("order:%s", in.Status)
	inits.Rdb.Set(inits.Ctx, orderKey, marshal, time.Minute*10)
	return &__.ListOrderResp{
		Code: 200,
		Msg:  "查询成功",
		List: orderList,
	}, nil
}
func (s Service) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {

	var user model.User
	model.FindUser(&user, int(in.UserId))
	if user.ID == 0 {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "该用户未登录",
		}, nil
	}
	var shop model.Shop
	model.FindShop(&shop, int(in.ShopId))
	if in.Quantity > int64(shop.Num) {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "库存不足",
		}, nil
	}
	if in.Address == "" {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "收货地址不能为空",
		}, nil
	}
	if in.Quantity <= 0 {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "购买数量不能小于0",
		}, nil
	}
	var order model.Order
	money := float64(in.Quantity) * shop.Price
	orderSn := pkg.UUId()
	order = model.Order{
		UserId:   int(in.UserId),
		ShopId:   int(in.ShopId),
		BizId:    int(in.BizId),
		OrderSn:  orderSn[:18],
		Address:  in.Address,
		Quantity: int(in.Quantity),
		Money:    money,
		Status:   in.Status,
		Year:     in.Year,
	}
	err := model.CreateOrder(&order)
	if err != nil {
		return &__.CreateOrderResp{
			Code: 0,
			Msg:  "下单失败",
		}, nil
	}
	var biz model.Biz
	model.FindBiz(&biz, int(in.BizId))
	if biz.Status == "在线" {
		pay := pkg.AliPay(orderSn, money)

		return &__.CreateOrderResp{
			Code: 200,
			Msg:  "下单成功",
			Data: pay,
		}, nil
	}
	num := int64(shop.Num) - in.Quantity
	shop = model.Shop{
		Model: gorm.Model{
			ID: uint(in.ShopId),
		},
		Num: int(num),
	}
	model.UpdateShop(&shop, int(in.ShopId))
	qrCode, _ := qr.Encode("http://www.topgoer.com", qr.M, qr.Auto)

	qrCode, _ = barcode.Scale(qrCode, 256, 256)

	file, _ := os.Create("shop.png")
	defer file.Close()

	png.Encode(file, qrCode)
	return &__.CreateOrderResp{
		Code: 200,
		Msg:  "支付成功",
	}, nil
}
